package com.sisucc.contractmanage.web.ContentSearch;

import com.sisucc.contractmanage.bean.ResultModel;
import com.sisucc.contractmanage.bean.contractES.ContractEsBean;
import com.sisucc.contractmanage.constant.ReturnStatusCode;
import com.sisucc.contractmanage.dao.contractES.ContractEsBeanRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author linyuqi
 */
@Log4j2
@RestController
@Api(tags = "内容检索")
public class ContentSearchController {

    @Autowired
    private ContractEsBeanRepository repository;

    @PostMapping("/queryContractByContentWithKeyWords")
    @ApiOperation(value = "根据关键字检索信息", httpMethod = "POST")
    public ResultModel queryContractByContentWithKeyWords(String keyWords, String currentPage, String pageSize) {
        ResultModel model = new ResultModel();
        HashMap<String, Object> params = new HashMap<>();
        params.put("keyWords", keyWords);
        log.info("根据关键字检索信息参数：" + params.toString());

        try {
            QueryBuilder queryBuilder = QueryBuilders.matchQuery("contractContent", keyWords);
            PageRequest pageRequest = PageRequest.of(Integer.parseInt(currentPage), Integer.parseInt(pageSize));
            Page<ContractEsBean> contractEsBeans = repository.search(queryBuilder, pageRequest);
//            log.info("关键字匹配的结果："+ contractEsBeans.getContent());
            model.setResultList(contractEsBeans.getContent());
            model.getResultMap().put("total", contractEsBeans.getTotalElements());
            model.getResultMap().put("pages", contractEsBeans.getTotalPages());
        } catch (Exception e) {
            e.printStackTrace();
            model.setStatusCode(ReturnStatusCode.ES_QUERY_ERROR);
            model.setResultMessage(ReturnStatusCode.ES_QUERY_ERROR_MESSAGE);
            log.info("根据关键字检索信息失败---程序执行失败！");
            return model;
        }
        return model;
    }
}
